<template>
  <div class="white-list">
    <div class="title">组织管理</div>
    <div>
      <el-form :inline="true" class="search-form">
        <el-col :span="19">
          <el-form-item>
            <el-input v-model="searchName" placeholder="输入组织名称" clearable @keyup.enter.native="queryList('search')">
              <el-button slot="append" class="search-icon" icon="icon-sousuo" @click="queryList('search')"></el-button>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-button
            v-if="permissionList.tenantmenu && rolesCode === 'ROLE_ADMIN'"
            class="filter-item"
            type="primary"
            size="14"
            @click="tenantMenu">套餐维护
          </el-button>
          <el-button type="primary" class="button-container" size="14" @click="handleAdd">新增组织</el-button>
        </el-col>
      </el-form>
    </div>
    <el-table
      v-loading="loading"
      :data="tableData"
      style="width: 100%"
      size="medium"
      :header-cell-style="{ background: '#F5F6F7' }">
      <el-table-column label="组织名称">
        <template slot-scope="scope">
          {{ scope.row.name || "-" }}
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作">
        <template slot-scope="scope">
          <el-button type="text" size="operate" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="text" :disabled="scope.row.id === '1'" size="operate" @click="handleDelete(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      :current-page="currentPage"
      :page-sizes="[10, 20, 50]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange">
    </el-pagination>

    <el-dialog
      :title="status === 'add' ? '新增组织' : '编辑组织'"
      :visible.sync="dialogVisible"
      width="628px"
      :before-close="handleClose"
      custom-class="tenant-dialog">
      <div>
        <el-form
          ref="form"
          class="define-form"
          :model="addFormData"
          :rules="rules"
          label-width="110px"
          label-position="right">
          <el-form-item label="组织名称" prop="name">
            <template #label>
              <span>组织名称</span>&nbsp;
              <el-tooltip content="支持中英文和标点符号,长度1-32个" placement="top">
                <i class="iconfont icon-wenhao"></i>
              </el-tooltip>
            </template>
            <el-input v-model="addFormData.name" placeholder="请输入组织名称" clearable></el-input>
          </el-form-item>
          <el-form-item v-if="status === 'edit'" label="组织ID" prop="phone">
            {{ addFormData.id }}
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button size="14" @click="handleClose">取 消</el-button>
        <el-button type="primary" size="14" @click="onsubmit">确 定 </el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { addObj, delObj, putObj, fetchPage } from '@/api/admin/tenant'
import { mapGetters } from 'vuex'
export default {
  name: "Tenant",
  data() {
    return {
      searchName: "", // 产品id或名称
      tableData: [], // 列表数据
      currentPage: 1, // 当前页码
      pageSize: 10, // 每页条数
      total: 0, // 列表数据总条数
      loading: true,
      dialogVisible: false,
      addFormData: {
        name: '',
        id: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入组织名称', trigger: 'blur' },
          { min: 1, max: 32, message: '长度在 1 到 32 个字符', trigger: 'blur' },
          { validator: this.validateTenantName, trigger: 'blur' }
        ]
      },
      status: ''
    }
  },
  computed: {
    ...mapGetters(['permissions', 'rolesCode']),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permissions.admin_systenant_add, false),
        delBtn: this.vaildData(this.permissions.admin_systenant_del, false),
        editBtn: this.vaildData(this.permissions.admin_systenant_edit, false),
        tenantmenu: this.vaildData(this.permissions.admin_systenant_tenantmenu, false)
      }
    }
  },
  created() {
    this.queryList()
  },
  methods: {
    validateTenantName(rule, value, callback) {
      const flag = new RegExp(/^[\u4E00-\u9FFFa-zA-Z\p{P}]+$/u).test(value)
      if (!flag) {
        callback(new Error('请使用规范名称'))
      } else {
        callback()
      }
    },

    /**
     * 查询组织列表
     * current 当前页码
     * size 每页条数
     * name 组织名称
     */
    queryList(condition) {
      this.currentPage = condition === 'search' ? 1 : this.currentPage
      this.loading = true
      const params = {
        current: this.currentPage,
        size: this.pageSize,
        name: this.searchName
      }
      fetchPage(params).then(res => {
        this.tableData = res.data.data.records
        this.total = res.data.data.total
      }).catch(err => {
        this.$message.error(err.message)
      }).finally(() => {
        this.loading = false
      })
    },
    // 新增组织
    handleAdd() {
      this.status = 'add'
      this.addFormData.name = ''
      this.dialogVisible = true
    },
    // 编辑组织
    handleEdit(params) {
      this.status = 'edit'
      this.addFormData.name = params.name
      this.addFormData.id = params.id
      this.dialogVisible = true
    },
    // 删除组织
    handleDelete(id) {
      this.$confirm('删除后将丢失将该组织下所有的数据，请谨慎操作', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delObj(id).then(res => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          this.queryList()
        }).catch(err => {
          this.$message.error(err.message)
        })
      })
    },
    // 每页条数改变时触发
    handleSizeChange(val) {
      this.pageSize = val
      this.queryList()
    },
    // 当前页变时触发
    handleCurrentChange(val) {
      this.currentPage = val
      this.queryList()
    },
    // 新增/编辑组织
    onsubmit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          const params = {
            ...this.addFormData
          }
          if (this.status === 'add') {
            addObj(params).then(res => {
              this.queryList()
            }).catch(err => {
              this.$message.error(err.message)
            })
          } else {
            putObj(params).then(res => {
              this.queryList()
            }).catch(err => {
              this.$message.error(err.message)
            })
          }
          this.dialogVisible = false
          this.$refs['form'].resetFields()
        } else {
          return false
        }
      })
    },
    // 关闭新增/编辑弹窗
    handleClose() {
      this.dialogVisible = false
      this.$refs['form'].resetFields()
    },
    // 套餐维护
    tenantMenu() {
      this.$router.push({
        path: '/admin/tenantmenu/index'
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.white-list {
  height: 100%;

  .title {
    font-size: 18px;
    font-weight: 600;
    color: #252525;
    margin-bottom: 21px;
  }

  .search-icon {
    cursor: pointer;
  }

  .button-container {
    float: right;
  }
}

.iconfont {
  margin-left: 2px;
  cursor: pointer;
}

.status-group {
  padding: 0 12px;

  .status-checkbox {
    display: block;
    height: 40px;
    line-height: 40px;
  }
}

.status-btn-box {
  text-align: center;
  border-top: 1px solid #E5E6E9;
  margin-top: 10px;

  .btn {
    margin-top: 10px;
  }
}

::v-deep .el-table__fixed-right-patch {
  background: #F5F6F7;
}

::v-deep .el-input-group__append {
  background: transparent;
}

::v-deep .tenant-dialog .el-dialog__body {
  padding: 20px 80px !important;
}
</style>
<style>
.custom-popover {
  min-width: 127px !important;
  padding: 12px 0;
}
</style>
